package fun.shuofeng.juc.sync;

/**
 * @author 朔风
 * @date 2024-01-28 15:41
 */
public class ThreadDemoShare {
    public static void main(String[] args) {
        Share share = new Share();
        // 创建多个线程
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "incr").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "decr").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "incr2").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "decr2").start();

    }
}

class Share {
    /**
     * 初始值
     */
    private int number = 0;

    /**
     * 加1
     */
    public synchronized void incr() throws InterruptedException {
        // 判断
        while (number != 0) {
            // number不等于1就等待
            this.wait();
        }
        // 干活
        number++;
        System.out.println(Thread.currentThread().getName() + "::" + number);
        // 通知
        this.notifyAll();
    }

    /**
     * 减1
     */
    public synchronized void decr() throws InterruptedException {
        // 判断
        while (number != 1) {
            this.wait();
        }
        // 干活
        number--;
        System.out.println(Thread.currentThread().getName() + "::" + number);
        // 通知
        this.notifyAll();
    }

}




